<template>
  <div class="chat">
    <el-card shadow="none">
      <el-form>
        <el-row>
          <el-col :span="6">
            <el-form-item>
              <el-input
                placeholder="请输入关键词"
                v-model="searchParams.keyword"
                style="margin-right: 20px"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item>
              <el-button type="primary" @click="onSearch">查询</el-button>
              <el-button type="primary" @click="onReset">重置</el-button>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item>
              <div style="text-align: right; width: 100%">
                <el-button type="primary" @click="onOpenPublish">发布</el-button>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <div style="padding: 20px 200px; overflow: auto">
      <el-row :gutter="12">
        <el-col :span="24" v-for="item in list" style="margin-bottom: 20px">
          <el-card>
            <template #header>
              <div
                class="card-header"
                style="display: flex; align-items: center; justify-content: space-between"
              >
                <span>
                  {{ item.title }}
                </span>
                <span>赞（{{ item.likeList.length }}）</span>
              </div>
            </template>
            <div class="comment-desc">{{ item.desc }}</div>
            <el-row class="comment-image" :gutter="12">
              <el-col :span="12" v-for="image in item.imageList">
                <el-image :src="image" alt="" style="height: 120px" />
              </el-col>
            </el-row>
            <template #footer>
              <!-- 评论区-->
              <div style="display: flex" class="comment-item" v-for="comment in item.commentList">
                <div style="padding-right: 12px">
                  <el-avatar
                    :size="24"
                    src="https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png"
                  />
                </div>
                <div style="flex-grow: 1">
                  <div class="comment-item-header">
                    <div style="display: flex;align-items: center">
                      <span>{{ comment.create_by }}</span>
                      <img @click="toChat(comment)" style="width: 20px;height: 20px;margin-left: 10px" src="@/assets/icon/chat.png" alt="">
                    </div>
                    <span style="text-align: right">{{ comment.create_time }}</span>
                  </div>
                  <div
                    class="comment-item-content"
                    style="padding: 10px 0; line-height: 16px; font-size: 14px; color: #666666"
                  >
                    {{ comment.content }}
                  </div>
                </div>
              </div>
              <div
                style="
                  display: flex;
                  align-items: center;
                  justify-content: center;
                  padding: 20px 0;
                  cursor: pointer;
                "
              >
                <span style="margin-right: 12px" @click="openComment(item)">评论</span>
                <span @click="onLike(item)">点赞</span>
              </div>
            </template>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <el-dialog v-model="showComment" title="评论" width="500">
      <el-form ref="commentFormRef" :mode="commentForm">
        <el-form-item prop="content">
          <el-input type="textarea" v-model="commentForm.content"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showComment = false">取消</el-button>
          <el-button type="primary" @click="onConfirmComment">提交</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="dialogVisible">
      <img w-full :src="dialogImageUrl" alt="Preview Image" />
    </el-dialog>
    <el-dialog v-model="show" title="发布" width="800">
      <el-form ref="publishFormRef" :mode="publishForm" label-position="top">
        <el-form-item prop="title" label="标题">
          <el-input v-model="publishForm.title"></el-input>
        </el-form-item>
        <el-form-item prop="desc" label="描述">
          <el-input type="textarea" v-model="publishForm.desc"></el-input>
        </el-form-item>
        <el-form-item prop="images" label="图片">
          <el-upload
            v-model:file-list="fileList"
            action="/v1/upload/file"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showPublish = false">取消</el-button>
          <el-button type="primary" @click="onConfirmPublish">提交</el-button>
        </div>
      </template>
    </el-dialog>


    <el-dialog v-model="showChat" title="聊天室" width="500" @close="closeChat">
      <div class="chat-list">
        <div v-for="item in chatList">
          <div class="chat-right" v-if="item.user_id == userId">
            <div class="chat-right-content" v-html="item.message"></div>
          </div>
          <div class="chat-left" v-else>
            <div class="chat-left-content" v-html="item.message">
            </div>
          </div>
        </div>
      </div>
      <div class="ai-footer">
        <div class="input-box">
          <input v-model="message" @keypress.enter="handeSend" type="text" placeholder="向AI提问..." style="border: none;outline: none;background: none;width: 100%;margin-left: 10px" />
          <img @click="handeSend" src="@/assets/icon/send.png" style="cursor:pointer;;width: 18px;height: 18px;margin-left: 10px" />
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script setup>
import { getContentList, addContent, addComment, addLike, getChatList, addChat } from '@/api/material';
import { Plus } from '@element-plus/icons-vue';
import { Message } from 'view-ui-plus';
import { onMounted, ref } from 'vue';
const searchParams = ref({
  keyword: '',
});

const onSearch = () => {
  getList();
};
const onReset = () => {
  searchParams.value.keyword = '';
};
const dialogImageUrl = ref('');
const dialogVisible = ref(false);

const handleRemove = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles);
};

const handlePictureCardPreview = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url;
  dialogVisible.value = true;
};
const show = ref(false);
const publishFormRef = ref(null);
const fileList = ref([]);
const publishForm = ref({
  title: '',
  desc: '',
  image: '',
});
const publishRules = {
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
};
const onConfirmPublish = () => {
  let imagesList = fileList.value.map((item) => {
    return item.response.data.url;
  });
  let image = imagesList.join(',');
  addContent({
    ...publishForm.value,
    image,
  }).then(() => {
    Message.success('发布成功');
    show.value = false;
    getList();
  });
};
const onOpenPublish = () => {
  show.value = true;
};

const list = ref([]);
const getList = () => {
  getContentList({
    keyword: searchParams.value.keyword,
  }).then((res) => {
    list.value = res.data.data.map((item) => {
      return {
        ...item,
        likeList: item.likeList || [],
        commentList: item.commentList || [],
        imageList: item.image.split(','),
      };
    });
  });
};
const showComment = ref(false);
const commentForm = ref({
  content_id: '',
  content: '',
});
const commentRules = ref({
  content: [{ required: true, message: '请输入评论内容' }],
});

const userId = ref(localStorage.getItem('token'))
const commentFormRef = ref(null);
const onConfirmComment = () => {
  addComment({
    user_id: localStorage.getItem('token'),
    create_by: localStorage.getItem('username'),
    content_id: commentForm.value.content_id,
    content: commentForm.value.content,
  }).then(() => {
    Message.success('评论成功');
    // 清空
    commentForm.value.content_id = '';
    commentForm.value.content = '';
    showComment.value = false;
    getList();
  });
};
const openComment = (item) => {
  commentForm.value = {
    content: '',
    content_id: item.id,
  };
  showComment.value = true;
};
const onLike = (item) => {
  addLike({
    user_id: localStorage.getItem('token'),
    create_by: localStorage.getItem('username'),
    content_id: item.id,
  }).then(() => {
    Message.success('点赞成功');
    getList();
  });
};
const showChat = ref(false);
const task = ref(null);
const closeChat = () => {
  clearInterval(task.value)
  task.value = null
}
const queryChatList = () => {
  getChatList({
    userId: localStorage.getItem('token'),
    friendId: friendId.value
  }).then(res => {
    chatList.value = res.data.data
  })
}
const toChat = item => {
  console.log(item)
  if (item.user_id === userId.value) {
    return
  } else {
    friendId.value = item.user_id
  }
  showChat.value = true;
  queryChatList()
  task.value = setInterval(() => {
    queryChatList()
  }, 5000)
}
const chatList = ref([]);
const message = ref('');
const friendId = ref('');
const handeSend = () => {
  if (!localStorage.getItem('token') ) {
    Message.error('未登录')
    return
  }
  if (!friendId.value) {
    Message.error('请选择聊天对象')
    return
  }
  if (localStorage.getItem('token') === friendId.value) {
    Message.error('不能和自己聊天')
    return
  }

  if (message.value.trim()) {
    addChat({
      user_id: localStorage.getItem('token'),
      message: message.value,
      friend_id: friendId.value
    }).then((res) => {
      console.log(res)
      chatList.value.push({
        ...res.data.data
      })
      message.value = ''
    })
  }
}
onMounted(() => {
  onSearch();
});
</script>
<style lang="less">
.comment-item {
  border-bottom: 1px solid #f0f0f0;
  padding-top: 12px;
  cursor: pointer;
  .comment-item-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}
.chat {
  height: 100vh;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  padding: 0 20px;
  padding-top: 70px;
  .comment-desc {
    padding: 12px 0;
    line-height: 24px;
    font-size: 12px;
    color: #666666;
  }
}


.chat-right {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  margin-top: 20px;
  .chat-right-content {
    border-radius: 12px;
    opacity: 1;
    background: #527AFC;
    padding: 15px;
    color: #ffffff;
    font-family: PingFang SC;
    font-size: 16px;
    color: #FFFFFF;
    line-height: 24px;
  }
}
.chat-left {
  margin-top: 20px;
  display: flex;
  align-items: center;
  justify-content: flex-start;
  .chat-left-content {
    border-radius: 12px;
    opacity: 1;
    background: #F2F5F8;
    font-family: PingFang SC;
    font-size: 16px;
    font-weight: 500;
    color: #3D3D3D;
    padding: 15px;
  }
}

.chat-list {
  min-height: 300px;
  max-height: 500px;
  flex-grow: 1;
  padding: 23px;
  overflow: auto;
}
.ai-footer {
  flex-shrink: 0;
  border-radius: 6px;
  opacity: 1;
  background: linear-gradient(90deg, #F1F6FF 0%, #F1F8FF 100%);
  padding: 15px;
  .input-box {
    border-radius: 24.5px;
    opacity: 1;
    background: #FFFFFF;
    padding: 0 20px;
    display: flex;
    align-items: center;
    height: 49px;
  }
}
</style>
